package com.hibay.goldking.net

import android.util.Log
import com.hibay.goldking.common.utils.MoshiHelper
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit


/**
 *
 *
 * @author chenchao
 * @date 3/1/21 11:23
 */
object RetrofitClient {
    private val httpLoggingInterceptor = HttpLoggingInterceptor(
        object : HttpLoggingInterceptor.Logger {
            private val mMessage = StringBuilder()
            override fun log(message: String) {
                Log.i("RetrofitClient", message)
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY)

    private val okHttpClient = OkHttpClient.Builder()
        .callTimeout(30, TimeUnit.SECONDS)
        .connectTimeout(30, TimeUnit.SECONDS)
        .addInterceptor(httpLoggingInterceptor)
        .addInterceptor(Interceptor.invoke {
            val request = it.request()
                .newBuilder()
                .build()
            it.proceed(request)
        })
        .build()

    val apiService: ApiService = creatRetrofit(ApiService.BASE_URL)

    private fun creatRetrofit(url: String): ApiService {
        return Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(url)
            .addConverterFactory(MoshiConverterFactory.create(MoshiHelper.moshi))
            .build().create(ApiService::class.java)
    }
}